package com.zhiqihang.ziqihangserverorders.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zhiqihang.order.Orders;
import com.zhiqihang.ziqihangserverorders.config.AliPayConfig;
import com.zhiqihang.ziqihangserverorders.repository.OrderRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName PayController
 * @Description Violet
 * @Author 86183
 * @Date 2024/7/14 14:30
 * @Version 1.0
 */
@Api(tags = "模拟支付")
@RestController
@RequestMapping("/alipay/")
@Slf4j
public class PayController {
    @Autowired
    private AliPayConfig aliPayConfig;
    @Autowired
    private OrderRepository orderRepository;

    /**APP ID，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值*/
    /**应用私钥，*/
    /**支付宝公钥*/
    /** 通知网址，用于处理支付宝完成支付处理后，你的应用中进行下一步处理的请求地址*/

    /**返回网址，用于支付宝完成支付处理后，重定向到某个位置*/
    private static final String RETURN_URL = "http://b3rhc8.natappfree.cc/alipay/finish";
    /*** 【固定】支付宝网关*/
    private static final String ALIPAY_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    /*** 【固定】加密算法*/
    private static final String ENCRYPTION_ALGORITHM = "RSA2";
    /*** 【固定】字符编码*/
    private static final String CHARSET = "UTF-8";
    /*** 【固定】数据格式*/
    private static final String DATA_FORMAT = "json";
    // 此方法用于接收客户端发起的支付请求，并响应支付表单页面到客户端
    // 网页客户端应该通过window.open直接向此处发起请求，则响应的支付表单会直接显示在window.open打开的窗口中
    @ApiOperation("支付宝沙箱支付")
    @ApiOperationSupport(order = 100)
    @GetMapping("pay")
    public void pay(Orders payParam, @ApiIgnore HttpServletResponse response) throws Exception {
        log.debug("payParam ="+payParam);
        AlipayClient alipayClient =
                new DefaultAlipayClient(ALIPAY_GATEWAY, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), DATA_FORMAT,
                                        CHARSET, aliPayConfig.getAlipayPublicKey(), ENCRYPTION_ALGORITHM);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());

        JSONObject bizContent = new JSONObject();
        Optional<Orders> optional = orderRepository.findById(payParam.getOutTradeNo());
        if (optional.isPresent()){
            Orders orders = optional.get();
            /**必传参数*/
            //商户订单号，商家自定义，保持唯一性
            bizContent.put("out_trade_no", orders.getOutTradeNo());
            //支付金额，最小值0.01元
            bizContent.put("total_amount", orders.getTotalAmount());
            //订单标题，不可使用特殊符号
            bizContent.put("subject", orders.getSubject());
            //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        }

        request.setBizContent("http://localhost:9090/order");
        request.setBizContent(bizContent.toString());
        String from = "";
        try {
            from = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        response.setContentType("text/html;charset="+CHARSET);
        response.getWriter().write(from);
        response.getWriter().flush();
        response.getWriter().close();
    }
    // 接收支付宝发送的通知（支付结果）
    // 注意：必须是POST请求
    @ApiIgnore
    @PostMapping("/notify")
    public String payNotify(@ApiIgnore HttpServletRequest request) throws Throwable {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content,
                sign, aliPayConfig.getAlipayPublicKey(), CHARSET); // 验证签名
        // 支付宝验签
        if (checkSignature) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家支付宝ID: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 你应该在此处补充支付成功后续的代码，例如修改订单状态等
            // 完成
            return "支付完成，商家将尽快发货";
        } else {
            return "支付失败，请返回订单页查看订单状态，或重新支付！";
        }
    }
    // 接收处理支付宝的跳转（支付完成后自动重定向到此处）
    @ApiIgnore
    @GetMapping("/finish")
    public String finish() {
        return "支付完成，请返回订单页查看订单状态！";
    }

}
